package com.hmall.search.service.impl;


import com.alibaba.fastjson.JSON;
import com.hmall.common.vo.PageVO;
import com.hmall.search.dto.SearchPageQueryDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    public static final String HMALL = "hmall";

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 页面查询
     *
     * @param searchPageQueryDTO 搜索页面查询 DTO
     * @return {@link PageVO}<{@link ItemDoc}>
     */
    @Override
    public PageVO<ItemDoc> pageQuery(SearchPageQueryDTO searchPageQueryDTO) {
        String key = searchPageQueryDTO.getKey();
        int page = Objects.isNull(searchPageQueryDTO.getPage()) ? 1 : searchPageQueryDTO.getPage();
        int size = Objects.isNull(searchPageQueryDTO.getSize()) ? 20 : searchPageQueryDTO.getSize();

        String sortBy = searchPageQueryDTO.getSortBy();
        String brand = searchPageQueryDTO.getBrand();
        String category = searchPageQueryDTO.getCategory();
        Integer minPrice = searchPageQueryDTO.getMinPrice();
        Integer maxPrice = searchPageQueryDTO.getMaxPrice();

        try {
            int from = (page - 1) * size;
            BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(key, brand, category, minPrice, maxPrice);

            SearchRequest request = new SearchRequest(HMALL);
            request.source().query(
                    new FunctionScoreQueryBuilder(
                            boolQueryBuilder,
                            new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                    new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                            // 参与算分的条件
                                            QueryBuilders.termQuery("isAD", true),
                                            ScoreFunctionBuilders.weightFactorFunction(10)
                                    )
                            }
                    ).boostMode(CombineFunction.SUM)
            ).from(from).size(size);
            // 销量，价格按降序进行排序
            if (!sortBy.equals("default") && StringUtils.isNoneEmpty(sortBy)) {
                request.source().sort(sortBy, SortOrder.DESC);
            }
            //高亮处理
            request.source().highlighter(
                    new HighlightBuilder()
                            .field("name")
                            .preTags("<em>")
                            .postTags("</em>")
                            .requireFieldMatch(false)
            );


            SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            SearchHit[] hits = search.getHits().getHits();

            List<ItemDoc> itemDocList = Arrays.stream(hits)
                    .map(
                            hit -> {
                                String sourceAsString = hit.getSourceAsString();
                                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                                ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);

                                if (highlightFields.size() > 0) {
                                    HighlightField highlightField = highlightFields.get("name");
                                    Text[] fragments = highlightField.getFragments();
                                    itemDoc.setName(String.valueOf(fragments[0]));
                                }

                                return itemDoc;

                            }
                    ).collect(Collectors.toList());
            PageVO<ItemDoc> itemDocPageVO = new PageVO<>();
            long value = search.getHits().getTotalHits().value;
            itemDocPageVO.setTotal(value);
            itemDocPageVO.setList(itemDocList);
            return itemDocPageVO;

        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 获取 Bool Query Builder
     *
     * @param key      关键字
     * @param brand    品牌
     * @param category 类别
     * @param minPrice 最低价格
     * @param maxPrice 最高价
     * @return {@link BoolQueryBuilder}
     */
    private BoolQueryBuilder getBoolQueryBuilder(String key, String brand, String category, Integer minPrice, Integer maxPrice) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNoneEmpty(key)) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        } else {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }
        if (StringUtils.isNoneEmpty(brand)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("brand", brand));
        }
        if (StringUtils.isNoneEmpty(category)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("category", category));
        }
        if (Objects.nonNull(minPrice) && Objects.nonNull(maxPrice)) {
            boolQueryBuilder.filter(
                    QueryBuilders.rangeQuery("price")
                            .gte(minPrice * 100)
                            .lte(maxPrice * 100)
            );


        }
        return boolQueryBuilder;
    }

    /**
     * 建议
     *
     * @param key 输入框的关键字
     * @return {@link List}<{@link String}>
     */
    @Override
    public List<String> suggestion(String key) {

        try {
            SearchRequest request = new SearchRequest(HMALL);

            String suggestions = "suggestions";
            request.source()
                    .suggest(
                            new SuggestBuilder()
                                    .addSuggestion(suggestions,
                                            SuggestBuilders.completionSuggestion("suggestion")
                                                    .prefix(key)
                                                    .skipDuplicates(true)
                                                    .size(10)
                                    )
                    );
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            CompletionSuggestion suggestion = response.getSuggest().getSuggestion(suggestions);
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            return options.stream().map(item -> item.getText().string()).collect(Collectors.toList());


        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }


        return null;
    }

    /**
     * 过滤 器
     *
     * @return {@link Map}<{@link String}, {@link List}<{@link String}>>
     */
    @Override
    public Map<String, List<String>> filters(SearchPageQueryDTO searchPageQueryDTO) {

        String key = searchPageQueryDTO.getKey();
        String brand = searchPageQueryDTO.getBrand();
        String category = searchPageQueryDTO.getCategory();
        Integer minPrice = searchPageQueryDTO.getMinPrice();
        Integer maxPrice = searchPageQueryDTO.getMaxPrice();

        SearchRequest searchRequest = new SearchRequest(HMALL);

        BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(key, brand, category, minPrice, maxPrice);
        String brandAgg = "brandAgg";
        String categoryAgg = "categoryAgg";
        searchRequest.source()
                .query(
                        boolQueryBuilder
                )
                .size(0)
                .aggregation(AggregationBuilders.terms(brandAgg)
                        .field("brand")
                        .size(10)
                )
                .aggregation(AggregationBuilders.terms(categoryAgg)
                        .field("category")
                        .size(10)
                );
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            Aggregations aggregations = searchResponse.getAggregations();
            ParsedStringTerms brands = aggregations.get(brandAgg);
            ParsedStringTerms categories = aggregations.get(categoryAgg);
            List<? extends Terms.Bucket> brandsBuckets = brands.getBuckets();
            List<? extends Terms.Bucket> categoriesBuckets = categories.getBuckets();
            List<String> brandList = brandsBuckets.stream()
                    .map(MultiBucketsAggregation.Bucket::getKeyAsString)
                    .collect(Collectors.toList());
            List<String> categoryList = categoriesBuckets.stream()
                    .map(MultiBucketsAggregation.Bucket::getKeyAsString)
                    .collect(Collectors.toList());
            HashMap<String, List<String>> map = new HashMap<>();
            map.put("brand", brandList);
            map.put("category", categoryList);
            return map;

        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }


        return null;
    }
}
